package com.clgc.eduservice.config.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtils {
    private static final String CLAIM_KEY_USERNAME = "sub";
    private static final String CLAIM_KEY_CREATED = "create";

    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * 生成token
     * @param userDetails
     * @return
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claim = new HashMap<>();
        claim.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        claim.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claim);
    }

    /**
     * 根据token获取用户名信息
     * @param token
     * @return
     */
    public String getUserNameFromToken(String token) {
        String username = null;
        try {
            Claims claims = getClaimFromToken(token);
            username= claims.getSubject();
            System.out.println("claim--->" + claims);
            System.out.println("username--->" + username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return username;
    }

    /**
     * 判断token是否失效
     * @param token
     * @param userDetails
     * @return
     */
    public boolean validateToken(String token,UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        return username.equals(userDetails.getUsername()) && isTokenExpired(token);
    }

    public boolean canRefreshToken(String token) {
        return !isTokenExpired(token);
    }

    public String refreshToken(String token) {
        Claims claim = getClaimFromToken(token);
        claim.put(CLAIM_KEY_CREATED, new Date());
        return generateToken(claim);
    }
    /**
     * 判断是否过期
     * @param token
     * @return
     */
    private boolean isTokenExpired(String token) {
        //不管是否过期，都返回claims对象
        Date expiration = getExpiredFromToken(token);
        return new Date(System.currentTimeMillis()).before(expiration);
    }

    /**
     * 获取过期时间
     * @param token
     * @return
     */
    private Date getExpiredFromToken(String token) {
        Claims claims = getClaimFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 根据claim生成JwtToken
     * @param claim
     * @return
     */
    private String generateToken(Map<String, Object> claim) {
        return Jwts.builder()
                .setClaims(claim)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    /**
     * token过期时间
     * @return
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 根据token获取claims
     * @param token
     * @return
     */
    private Claims getClaimFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            claims = e.getClaims();
        }
        return claims;
    }
}
